using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace sforceExplorer
{
	/// <summary>
	/// Summary description for frmLogin.
	/// </summary>
	public class frmLogin : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnLogin;
		private System.Windows.Forms.TextBox txtPassword;
		private System.Windows.Forms.TextBox txtUsername;
		private System.Windows.Forms.Label lblUsername;
		private System.Windows.Forms.Label lblPassword;
		private System.Windows.Forms.ListBox lbUserNames;
		private System.Windows.Forms.Button btnCancel;
        private Label label1;
        private TextBox txtToken;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public frmLogin()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			this.lbUserNames.Top = this.txtUsername.Top + 19;
			this.lbUserNames.Left = this.txtUsername.Left;
			this.lbUserNames.Width = this.txtUsername.Width;
			this.txtUsername.Text = GlobalProperties.userName;
			this.txtPassword.Text = GlobalProperties.password;
            this.txtToken.Text = GlobalProperties.token;
			this.lbUserNames.Visible = false;

			this.txtUsername.KeyUp += new KeyEventHandler(txtUsername_KeyUp);
			this.txtUsername.LostFocus +=new EventHandler(txtUsername_LostFocus);
			this.txtUsername.GotFocus +=new EventHandler(txtUsername_GotFocus);
			this.lbUserNames.KeyUp +=new KeyEventHandler(lbUserNames_KeyUp);
			this.lbUserNames.Click +=new EventHandler(lbUserNames_Click);

		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.btnLogin = new System.Windows.Forms.Button();
            this.txtPassword = new System.Windows.Forms.TextBox();
            this.txtUsername = new System.Windows.Forms.TextBox();
            this.lblUsername = new System.Windows.Forms.Label();
            this.lblPassword = new System.Windows.Forms.Label();
            this.lbUserNames = new System.Windows.Forms.ListBox();
            this.btnCancel = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.txtToken = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // btnLogin
            // 
            this.btnLogin.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnLogin.Location = new System.Drawing.Point(312, 16);
            this.btnLogin.Name = "btnLogin";
            this.btnLogin.Size = new System.Drawing.Size(88, 24);
            this.btnLogin.TabIndex = 5;
            this.btnLogin.Text = "Login";
            this.btnLogin.Click += new System.EventHandler(this.btnLogin_Click);
            // 
            // txtPassword
            // 
            this.txtPassword.Location = new System.Drawing.Point(96, 48);
            this.txtPassword.Name = "txtPassword";
            this.txtPassword.PasswordChar = '*';
            this.txtPassword.Size = new System.Drawing.Size(208, 20);
            this.txtPassword.TabIndex = 4;
            this.txtPassword.Text = "123456";
            // 
            // txtUsername
            // 
            this.txtUsername.Location = new System.Drawing.Point(96, 16);
            this.txtUsername.Name = "txtUsername";
            this.txtUsername.Size = new System.Drawing.Size(208, 20);
            this.txtUsername.TabIndex = 3;
            this.txtUsername.Text = "mobile2@merce.com";
            this.txtUsername.TextChanged += new System.EventHandler(this.txtUsername_TextChanged);
            // 
            // lblUsername
            // 
            this.lblUsername.Location = new System.Drawing.Point(16, 16);
            this.lblUsername.Name = "lblUsername";
            this.lblUsername.Size = new System.Drawing.Size(80, 23);
            this.lblUsername.TabIndex = 7;
            this.lblUsername.Text = "Username:";
            // 
            // lblPassword
            // 
            this.lblPassword.Location = new System.Drawing.Point(16, 48);
            this.lblPassword.Name = "lblPassword";
            this.lblPassword.Size = new System.Drawing.Size(80, 23);
            this.lblPassword.TabIndex = 6;
            this.lblPassword.Text = "Password:";
            // 
            // lbUserNames
            // 
            this.lbUserNames.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.lbUserNames.Location = new System.Drawing.Point(288, 144);
            this.lbUserNames.Name = "lbUserNames";
            this.lbUserNames.Size = new System.Drawing.Size(208, 106);
            this.lbUserNames.TabIndex = 19;
            this.lbUserNames.Visible = false;
            this.lbUserNames.SelectedIndexChanged += new System.EventHandler(this.lbUserNames_SelectedIndexChanged);
            // 
            // btnCancel
            // 
            this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnCancel.Location = new System.Drawing.Point(312, 48);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(88, 24);
            this.btnCancel.TabIndex = 5;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(19, 75);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(38, 13);
            this.label1.TabIndex = 20;
            this.label1.Text = "Token";
            this.label1.Click += new System.EventHandler(this.label1_Click);
            // 
            // txtToken
            // 
            this.txtToken.Location = new System.Drawing.Point(96, 75);
            this.txtToken.Name = "txtToken";
            this.txtToken.Size = new System.Drawing.Size(208, 20);
            this.txtToken.TabIndex = 21;
            // 
            // frmLogin
            // 
            this.AcceptButton = this.btnLogin;
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(416, 102);
            this.ControlBox = false;
            this.Controls.Add(this.txtToken);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.lbUserNames);
            this.Controls.Add(this.lblUsername);
            this.Controls.Add(this.lblPassword);
            this.Controls.Add(this.btnLogin);
            this.Controls.Add(this.txtPassword);
            this.Controls.Add(this.txtUsername);
            this.Controls.Add(this.btnCancel);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.KeyPreview = true;
            this.Name = "frmLogin";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Login to salesforce.com";
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		private bool login(string username, string password, string token)
		{
			try 
			{
				if (GlobalProperties.endPoint.Length > 0) 
				{
					Utility.binding.Url = GlobalProperties.endPoint;
				}
				if (GlobalProperties.useProxy) 
				{
					Utility.binding.Url = Utility.binding.Url.Replace("https:", "http:");
					Utility.binding.Proxy = new System.Net.WebProxy(GlobalProperties.proxyServer, Convert.ToInt16(GlobalProperties.proxyPort));
				} 
				else 
				{
					Utility.binding.Proxy = null;
				}

				if (GlobalProperties.clientId.Length > 0) 
				{
					Utility.binding.CallOptionsValue = new sforce.CallOptions();
					Utility.binding.CallOptionsValue.client = GlobalProperties.clientId;
				}
				if (GlobalProperties.noHTTPS)
					Utility.binding.Url = Utility.binding.Url.Replace("https:", "http:");
                if (token != null)
                {
                    password += token;
                }

                try
                {
                    Utility.loginResult = Utility.binding.login(username, password);
                }
                catch (System.Net.WebException e)
                {
                    MessageBox.Show("Login error: " + e.Message);
                    return false;
                }
				Utility.binding.SessionHeaderValue = new sforce.SessionHeader();
				Utility.binding.SessionHeaderValue.sessionId = Utility.loginResult.sessionId;
				Utility.binding.Url = Utility.loginResult.serverUrl;
				
				if (GlobalProperties.useProxy)
					Utility.binding.Url = Utility.binding.Url.Replace("https:", "http:");

				if (GlobalProperties.noHTTPS)
					Utility.binding.Url = Utility.binding.Url.Replace("https:", "http:");

				GlobalProperties.userName = this.txtUsername.Text;
				GlobalProperties.password = this.txtPassword.Text;
                GlobalProperties.token = this.txtToken.Text;
				GlobalProperties.sessionId = Utility.loginResult.sessionId;
				GlobalProperties.endPoint = Utility.loginResult.serverUrl;
				GlobalProperties.UserId = Utility.loginResult.userId;
				return true;
			} 
			catch (Exception ex) 
			{
				System.Windows.Forms.MessageBox.Show("Login failed: " + ex.Message, "Partner Sample", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
				return false;
			}
		}

		private void txtUsername_KeyUp(object sender, KeyEventArgs e)
		{
			if (lbUserNames.Visible)
			{
				if (e.KeyCode.Equals(System.Windows.Forms.Keys.Down))
				{
					this.txtUsername.TextChanged -= new EventHandler(txtUsername_TextChanged);
					lbUserNames.Focus();
					lbUserNames.SelectedIndex = 0;
					this.AcceptButton = null;
				} 
				else if (e.KeyCode.Equals(System.Windows.Forms.Keys.Enter)) 
				{
					lbUserNames.Visible = false;
					this.AcceptButton = this.btnLogin;
				}
			}
		}

		private void txtUsername_LostFocus(object sender, EventArgs e)
		{
			this.txtUsername.TextChanged -= new EventHandler(txtUsername_TextChanged);
		}

		private void txtUsername_GotFocus(object sender, EventArgs e)
		{
			this.txtUsername.TextChanged += new EventHandler(txtUsername_TextChanged);
		}

		private void lbUserNames_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.KeyCode.Equals(System.Windows.Forms.Keys.Enter) )
			{
				this.txtUsername.TextChanged += new EventHandler(txtUsername_TextChanged);
				this.lbUserNames.Visible = false;
				this.AcceptButton = this.btnLogin;
			}
		}

		private void lbUserNames_Click(object sender, EventArgs e)
		{
			this.lbUserNames.Visible = false;
		}

		private void LoadListBox(string prefix) 
		{

			this.lbUserNames.Items.Clear();
			if (prefix.Length > 0) 
			{
				IEnumerator ienum = GlobalProperties.LoginHistory.GetEnumerator();
				while (ienum.MoveNext())
				{
					if (((UserCredentials)ienum.Current).UserName.StartsWith(prefix))
						lbUserNames.Items.Add(ienum.Current);
				}
			}
		}

		private void txtUsername_TextChanged(object sender, System.EventArgs e)
		{
			LoadListBox(txtUsername.Text);
			lbUserNames.Visible = lbUserNames.Items.Count > 0;
		}

		private void btnLogin_Click(object sender, System.EventArgs e)
		{
			Cursor = Cursors.WaitCursor;

			if (login(this.txtUsername.Text, this.txtPassword.Text, this.txtToken.Text)) 
			{
				GlobalProperties.AddToLoginHistory(this.txtUsername.Text, this.txtPassword.Text, this.txtToken.Text);
				this.DialogResult = System.Windows.Forms.DialogResult.OK;
			} 
			else 
			{
				this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			}
			Cursor = Cursors.Default;
			this.Hide();
		}

		private void lbUserNames_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (lbUserNames.SelectedItem != null) 
			{
				UserCredentials uc = (UserCredentials)lbUserNames.SelectedItem;
				this.txtUsername.Text = uc.UserName;
				this.txtPassword.Text = uc.Password;
                this.txtToken.Text = uc.Token;
			}
		}

		private void btnCancel_Click(object sender, System.EventArgs e)
		{
			this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.Hide();
		}

        private void label1_Click(object sender, EventArgs e)
        {

        }
	}
}
